<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class RegionGroups extends CI_Model {

	function __construct() {
        parent::__construct();
    }

    public function exists($regionGroup) {
        $exists = false;

        $id = self::getId($regionGroup);
        $exists = ($id > 0);

        return $exists;
    }

    public function getAll() {
    	$sql = "SELECT " .
				"rg.RegionGroupId AS Id," .
				"rg.RegionGroup,". 
				"rg.Description " .
				"FROM " .
				"regiongroups AS rg ". 
				"WHERE " .
				"(rg.CountryId = " . COUNTRY_ID . ") " .
				"ORDER BY " .
				"`RegionGroup`";

		$query = $this->db->query($sql);
		$result = array();

		if ($query->num_rows() > 0) {
			foreach ($query->result_array() as $row) {
				array_push($result, $row);
			}
		}

		return $result;
    }

    public function getId($regionGroup) {
        $sql = "SELECT " .
               "`RegionGroupId` AS `Id` " .
               "FROM " .
               "`regiongroups` AS `rg` " .
               "WHERE " .
               "(`CountryId` = " . COUNTRY_ID . ") AND " .
               "(`RegionGroup` LIKE " . $this->db->escape((string)$regionGroup)  . ")";

        $query = $this->db->query($sql);

        $id = 0;

        if ($query->num_rows() > 0) {
            $row = $query->row_array();
            $id = $row['Id'];
        }

        return $id;
    }

    public function save($data) {
    	$saved = true;

    	if ($data != null) {
    		$this->db->trans_begin();

    		foreach ($data as $row) {
    			$state = $row->RowState;
    			$sql = '';

    			$values = array();

    			if ($state == 'added') {
    				date_default_timezone_set('Asia/Hong_Kong');

    				array_push($values, COUNTRY_ID);
    				array_push($values, $row->RegionGroup);
    				array_push($values, $row->Description);

    				$sql =  "INSERT INTO `regiongroups` (`CountryId`, `RegionGroup`, `Description`, `DateCreated`) VALUES (?, ?, ? , NOW())";
    			}
    			else if ($state == 'modified') {
					array_push($values, $row->RegionGroup);
    				array_push($values, $row->Description);
    				array_push($values, $row->Id);
    			
    				$sql = "UPDATE `regiongroups` SET `RegionGroup` = ?, `Description` = ? WHERE (`RegionGroupId` = ?)";

    			}
    			else if ($state == 'deleted') {
    				array_push($values, $row->Id);
    				$sql = "DELETE FROM `regiongroups` WHERE (`RegionGroupId` = ?)";
    			}
    			else {

    			}

    			if (trim($sql) != '') $this->db->query($sql, $values); 
    		}

    		if ($this->db->trans_status() === FALSE) {
                $this->db->trans_rollback();
                $saved = false;
            }
            else {
                $this->db->trans_commit();
            }
    	}

    	return $saved;
    }

}